package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class ProducerQuickStart {

    public static void main(String[] args) throws Exception {
        // 1. 定义kafka的配置信息
        Properties properties = new Properties();
        // 1.1 设置kafka服务器连接信息
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        // 1.2 设置key和value的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        // 1.3 ack机制
        properties.put(ProducerConfig.ACKS_CONFIG,"1");
        // 1.4 最大重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,10);
        // 1.5 压缩算法
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");
        // 2. 创建生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);
        // 3. 通过生产者对象发送消息
        ProducerRecord<String,String> producerRecord = new ProducerRecord<>("itheima-topic","key001","hello kafka");
        // ProducerRecord<String,String> producerRecord = new ProducerRecord<>("itheima-topic","hello kafka");

        // 同步发送
        // RecordMetadata recordMetadata = producer.send(producerRecord).get();
        // 异步发送
        producer.send(producerRecord, new Callback() {
            /**
             * 发送完成(完成不代表是成功)后自动回调的方法
             * @param recordMetadata
             * @param e
             */
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (e != null){
                    // 记录日志
                    e.printStackTrace();
                }else {
                    // 发送成功
                    System.out.println(recordMetadata.partition());
                    System.out.println(recordMetadata.offset());
                }
            }
        });

        // 4. 关闭消息通道
        producer.flush();
        producer.close();


    }
}
